import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

final class LocalStorages {
  LocalStorages._internal();

  static SharedPreferences? _shared;
  static SharedPreferences? get shared => _shared;

  /// 为了确保本地的数据可以提前被加载进来
  /// 如果不这样做的话，后续的所有操作都需要通过异步的方式来操作，很麻烦
  /// 具体为什么是异步的，你可以去查一下这个组件相关的特性，此处不过多的说明；
  static Future<SharedPreferences?> ensureInitialized() async {
    if (_shared == null) {
      SharedPreferences.setPrefix("top.xbaistack."); // 设置统一的前缀
      _shared = await SharedPreferences.getInstance();
    }
    return _shared;
  }

  static void remove(String key) => _shared?.remove(key);

  static void set(String key, Object value) {
    if (value is int) {
      _shared?.setInt(key, value);
    } else if (value is bool) {
      _shared?.setBool(key, value);
    } else if (value is double) {
      _shared?.setDouble(key, value);
    } else if (value is List<String>) {
      _shared?.setStringList(key, value);
    } else {
      _shared?.setString(key, value is String ? value : value.toString());
    }
  }

  static void setJson(String key, Object value) {
    _shared?.setString(key, json.encode(value));
  }

  static int getInt(String key, [int? defValue]) {
    return _shared?.getInt(key) ?? defValue ?? 0;
  }

  static double getDouble(String key, [double? defValue]) {
    return _shared?.getDouble(key) ?? defValue ?? 0.0;
  }

  static bool isEnabled(String key, [bool? defValue]) {
    return (_shared?.getBool(key) ?? defValue) == true;
  }

  static bool isDisabled(String key, [bool? defValue]) {
    return (_shared?.getBool(key) ?? defValue) == false;
  }

  static String getString(String key, [String? defValue]) {
    return _shared?.getString(key) ?? defValue ?? "";
  }

  static List<String> getArray(String key, [List<String>? defValue]) {
    return _shared?.getStringList(key) ?? defValue ?? <String>[];
  }

  static T getJsonObject<T>(
    String key,
    T Function(Map<String, dynamic>) converter,
  ) {
    String content = getString(key, "{}");
    return converter.call(json.decode(content));
  }

  static List<T> getJsonArray<T>(
    String key,
    T Function(Map<String, dynamic>) converter,
  ) {
    String content = getString(key, "[{}]");
    List<Map<String, dynamic>> items = json.decode(content);
    return items.map(converter).toList();
  }
}
